package com.he.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.he.common.dto.LoginDto;
import com.he.common.lang.Result;
import com.he.entity.User;
import com.he.service.UserService;
import com.he.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;

/**
 * @author Kris He
 * @date 2022/04/10 17:49
 * DTO代表服务层需要接收的数据和返回的数据 而VO代表展示层需要显示的数据。
 **/
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        //获取单个信息，通过条件构造调用equals
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        //断言，如果为空则用户不存在
        Assert.notNull(user,"用户不存在");
        //校验密码
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        //密码正确，则通过jwtUtils获取jwt
        String jwt = jwtUtils.generateToken(user.getId());
        //一般来说把jwt放入header的属性Authorization里，因此引入形参response
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-control-Expose-Headers","Authorization");
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    // 退出
    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            subject.logout();
            return Result.succ(null);
        }
        return Result.fail("退出失败");
    }

}


